//兼容旧广告脚本 strat----
var BuildClientAnalysisDataforOneAD = function(){ return "";}
function DoADClick(url, caData, isPreview) {
    if (!(url.indexOf("javascript") < 0)) {
      url = decodeURIComponent(url);
      url = url.substring(11, url.length);
      eval(url);
    } else {
      window.open(url, "_blank");
    }
}
// 获取cookie方法
function _icbcHitGetCookie(name) {
    var reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"),
        arr = document.cookie.match(reg);
    if (arr) return unescape(arr[2]);
    else return null;
}
//客户端下载记录控件专用
function recordAppAndDownload(appUrl, appName) {
    try {
        var url = "/ICBCAppDownload/mobileapp/" + appName;
        window.open(appUrl);
        var nJSParam = {
            rid: new Date().getTime(),
            pageUrl: encodeURI(window.location.href),
            ReferrerPage: encodeURI(url),
            ICBCPostingPath: encodeURI("http://"+location.hostname+getMetaInfo("CurrentColumnPath")+"/"+getMetaInfo("CurrentPageName")+".htm"),
            UserAnalysisId: icbcUserAnalysisId,
            UserAnalysisGeoPos: encodeURI(localStorage.getItem("ICBCAnalysisLocationPosition")||"[]")
        };
    } catch (exp) {}
}
//兼容旧广告脚本 end-----
var disableBP = false;
(function () {
    var topHref = decodeURI(top.location.href);
    if(topHref.search(/\/\/(spain.icbc.com.cn|big5.icbc.com.cn)/) > -1) { disableBP=true;}
})();
// hitConfig读变量,变量集中在config.js文件中
var hitConfig = window.appConfig.hit||{};
//初始化埋点参数
var icbcUserAnalysisId = getUserAnalysisId();
var userAgent = navigator.userAgent;
var channelType = ["1","3","4"].indexOf(getChannel()) >-1 ? "1":"0";//0-pc 1-手机
var transitionId = getQueryString("transitionid");
var srcPage =JSON.parse(sessionStorage.getItem("srcinfo")||"{}");
// 页面信息：通过cms系统采编的页面，头部信息都会有meta标签，会记录这些信息
var curPage = {
    channel: getChannel(), //当前渠道
    columnId: getMetaInfo("CurrentColumn"),//当前页面栏目id
    columnPath: getMetaInfo("CurrentColumnPath"), //当前页面栏目路径
    pageName: getMetaInfo("CurrentPageName"),//当前页面名称
    pageId: getMetaInfo("CurrentPageId"), //当前页面id
    pageUrl: getMetaInfo("CurrentPageUrl")||location.href, // 当前页面url
    pageAccessId: guid() //当前页面访问标识：相当于页面唯一id，可以用来统计访问路径
};
!disableBP && sessionStorage.setItem("srcinfo",JSON.stringify(curPage));
var p_bp_init_param = JSON.stringify({
    p_scr: screen.width + "*" + screen.height,  // 分辨率
    p_lg: navigator.language || navigator.browserLanguage,  // 语言
    p_user_analysis_id: icbcUserAnalysisId,   // （由于我们没有用户概念）相当于拟一个用户id：日期+随机数 => 以前做埋点时沿用下来的字段，一旦生成会存在localStroage中，不过期，除非换浏览器或清缓存
    p_pv_type: getPvType(),  // 埋点事件类型
    p_search_word:"",
    p_inject_channel:"",
    p_transaction_name:"",
    p_transaction_code:"",
    p_cur_channel: curPage.channel,   // 当前页面信息：当前从meta标签取
    p_cur_column_path: curPage.columnPath,
    p_cur_column_id: curPage.columnId,
    p_cur_page_name: curPage.pageName,
    p_cur_page_id: curPage.pageId,
    p_cur_page_url: curPage.pageUrl,
    p_cur_page_access_id: curPage.pageAccessId,
    p_src_channel: srcPage.channel,   // 来源页面信息：来源从sessionStroage中取
    p_src_column_path: srcPage.columnPath,
    p_src_column_id: srcPage.columnId,
    p_src_page_name: srcPage.pageName,
    p_src_page_id: srcPage.pageId,
    p_src_page_url: srcPage.pageUrl,
    p_src_page_access_id: srcPage.pageAccessId,
    p_browser: getBrowser(),  // 获取当前使用的浏览器
    p_search_engine: getSearchEngine()  // 获取搜索引擎，从哪个搜索引擎跳过来的
});

/**
 * 禁用埋点
 */
(function () {
    try {
        if (typeof jQuery === 'undefined') {
            !disableBP && icbchitInit();
            return;
        }
        var cookieAlertConfig = "";
        var ICBCCookieUse = localStorage.getItem("USE_COOKIE") == 1 ? true : false;
        if (ICBCCookieUse) {
            icbchitInit();
            return;
        }
        // 为解决客行问题，先特殊处理，后续优化
        if (/korea/gi.test(location.host)) {
            $.ajax({
                url: '//' + window.appConfig.v.host + '/userfiles/resources/icbc/cookie/alertconfig.json',
                dataType: 'text',
                xhrFields: {
                    withCredentials: false,
                },
            }).done(function (data) {
                var hostName = window.location.hostname;
                data = JSON.parse(data);
                if (data[hostName]) {
                    var hostConfig = data[hostName];
                    var defaultLang = hostConfig['default'];
                    //新url判断
                    var match = window.location.pathname.match(/\/([a-zA-Z]+)\/(page|column)/);
                    var lang = match && match[1] ? match[1] : defaultLang;
                    cookieAlertConfig = data[hostName][lang] || data[hostName][defaultLang];
                    disableBP = true; //禁用埋点、客行等
                    clearCookieAndStorage();
                    $(document).ready(function () { 
                        $("body").append(
                        '<style>\
                            #icbccookieuse {\
                                position:fixed;width:100%;z-index:1000;bottom:0;text-align:left;background-color:#e8e8e8;\
                            }\
                            #icbccookieuse button{\
                                cursor:pointer;margin-right:20px;border: 1px solid #c9000d;padding: 3px 15px;border-radius: 4px;font-size: 12px;outline: none;color: #c9000d;\
                            }\
                            #icbccookieuse .btn-confirm{\
                                background-color: #c9000d;color: #fff;\
                            }\
                        </style>\
                        <div id="icbccookieuse">\
                            <div style="width: 30%;margin: 0 auto;padding:20px">'+ cookieAlertConfig.content +'</div>\
                            <div style="width: 30%;margin: 0 auto;text-align: right; margin-bottom: 15px;">\
                                <button class="btn-confirm"  onclick="handleCookieConfirm()">'+ cookieAlertConfig.confirm +'</button>\
                                <button onclick="clearCookieAndStorage();">'+ cookieAlertConfig.cancel +'</button>\
                            </div>\
                        </div>'
                        )
                    });
                } else {
                    !disableBP && icbchitInit();
                }
            }).fail(function (err) {
                !disableBP && icbchitInit();
            });
        } else {
            !disableBP && icbchitInit();
        }
    } catch (error) {
        !disableBP && icbchitInit();
    }
})();

function clearCookieAndStorage() {
    localStorage.clear();
    sessionStorage.clear();
    var keys = document.cookie.match(/[^ =;]+(?=\=)/g)
    if(keys) {
        for(var i = keys.length; i--;){
            document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
        }
    }
    $("#icbccookieuse").hide();
}

function handleCookieConfirm() {
    $("#icbccookieuse").hide();
    disableBP = false;
    localStorage.setItem("USE_COOKIE",1);
    icbchitInit();
}

/**
 * 初始化：主方法
 */
function icbchitInit() {
    //加载埋点SDK：加载埋点公共控件
    loadSugoioSDK();
    //发送新客行：参数赋值
    var ref = document.referrer;
    if(ref && srcPage.columnPath && srcPage.pageName){
        var refArray =  ref.split("/");
        ref = refArray[0]+"//"+ refArray[2] + srcPage.columnPath + '/' + srcPage.pageName + ".htm";
    }
    var oldPageUrl = "http://"+location.hostname+getMetaInfo("CurrentColumnPath")+ "/"+ getMetaInfo("CurrentPageName")+".htm";
    var nJSParam = { 
        rid: new Date().getTime(),
        pageUrl: encodeURI(oldPageUrl),
        ReferrerPage: encodeURI(ref),
        ICBCPostingPath: encodeURI(oldPageUrl),
        UserAnalysisId: icbcUserAnalysisId,
        UserAnalysisGeoPos: encodeURI(localStorage.getItem("ICBCAnalysisLocationPosition")||"[]")
    };

    if (userAgent.search(/(newemallversion|f-wapb)/i) > -1) {
        if (typeof ICBCUtil === 'undefined') {
            $.ajax({
                url:"https://"+window.appConfig.mywap2.host+"/ICBCWAPBank/ebdpui/icbc_core.js",
                dataType: "script",
                timeout: 2000,
                xhrFields: {
                    withCredentials: false,
                },
            }).done(function(){
                handleICBCCoreJsLoaded();
            }).fail(function(){
                //失败、超时未加载直接发送埋点
                initSugoioSDK(); 
            });
        } else {
            handleICBCCoreJsLoaded();
        }
    } else {
        //初始化公共埋点SDK
        initSugoioSDK();
    }
    if(typeof jQuery == "undefined") return;
    $(document).ready(function() {
        //为所有data-collecting-sign类添加点击事件，触发站内点击类型的埋点事件
        $(".data-collecting-sign").on("click", function(e) {
            var self = $(this);
            var attr = self.data();
            var param = JSON.parse(p_bp_init_param);
            param.p_pv_type ="2";
            handleClientHit({
                buttonname: attr.collectingWname || self[0].innerText,
                areanoname: getAreaName(self),
                word1: JSON.stringify(param),
                // 因sdk无法覆盖，暂时先用word4记录buttonname，后端同步覆盖buttonname值
                word4: attr.collectingWname || self[0].innerText,
            });
        });
        //为所有data-collecting-inject类添加点击事件，触发交易注入控件埋点事件
        $(".data-collecting-inject").on("click", function() {
            var attr = $(this).data();
            var param = JSON.parse(p_bp_init_param);
            param.p_pv_type ="5";
            param.p_inject_channel = attr.injectChannel;
            param.p_transaction_code = attr.transactionCode;
            param.p_transaction_name = attr.transactionName;
            var shareuser = ""
            try {
                if (location.search) {
                    var bankDetailA = location.search.split("&").filter(function(item) {
                        return item.search("shareuser=") >= 0;
                    });
                    if (bankDetailA.length > 0) {
                        shareuser = bankDetailA[0].split("shareuser=")[1];
                    }
                }
            } catch (error) {
                console.log(error)
            }
            handleClientHit({
                word1: JSON.stringify(param),
                word3: shareuser ? shareuser : ''
            })
        });
    }); 
}

/**
 * 加载埋点SDK：公共埋点控件
 */
function loadSugoioSDK() {
    try {
        var SUGOIO_CUSTOM_LIB_URL = "/resource/lib/sugoio/sugoio-latest.min.js";//无码sdk地址
        var BEFORE_INIT={async: false};//配置是否异步，若不配置默认为异步，true代表异步，false代表同步。
        !function(a,r){var e=!0,o=function u(){var e=navigator.userAgent.toLowerCase(),o={},t={IE:window.ActiveXObject||"ActiveXObject"in window,Chrome:-1<e.indexOf("chrome")&&-1<e.indexOf("safari"),Firefox:-1<e.indexOf("firefox"),Opera:-1<e.indexOf("opera"),Safari:-1<e.indexOf("safari")&&-1==e.indexOf("chrome"),Edge:-1<e.indexOf("edge"),QQBrowser:/qqbrowser/.test(e),WeixinBrowser:/MicroMessenger/i.test(e)};for(var r in t)if(t[r]){var n="";if("IE"==r)n=e.match(/(msie\s|trident.*rv:)([\w.]+)/)[2];else if("Chrome"==r){for(var i in navigator.mimeTypes)"application/360softmgrplugin"==navigator.mimeTypes[i].type&&(r="360");n=e.match(/chrome\/([\d.]+)/)[1]}else"Firefox"==r?n=e.match(/firefox\/([\d.]+)/)[1]:"Opera"==r?n=e.match(/opera\/([\d.]+)/)[1]:"Safari"==r?n=e.match(/safari\/([\d.]+)/)[1]:"Edge"==r?n=e.match(/edge\/([\d.]+)/)[1]:"QQBrowser"==r&&(n=e.match(/qqbrowser\/([\d.]+)/)[1]);o.type=r,o.versions=parseInt(n)}return o}();if(o?("Chrome"==o.type&&o.versions<=20||"IE"==o.type&&o.versions<=8||"Firefox"==o.type&&o.versions<=10||"safari"==o.type&&o.versions<=9)&&(e=!1):e=!1,!e)return window.sugoio={},window.sugoio.init=function(){},window.sugoio.callback=function(){};if(!r.__SV){var t,n,i=window,s="sugoio";i[s]=r;try{!function f(e){var o=i.atob(e),t=JSON.parse(o).state,r={accessToken:t.access_token,accessTokenExpiresAt:Date.now()+1e3*Number(t.expires_in),projectToken:t.token,projectId:t.project_id,userId:t.user_id,choosePage:t.choose_page,trackType:t.trackType};i.sessionStorage.setItem("editorParams",JSON.stringify(r)),t.hash?i.location.hash=t.hash:i.history?i.history.replaceState("",a.title,i.location.pathname+i.location.search):i.location.hash=""}(i.location.hash.replace("#",""))}catch(p){}finally{!function l(n){var i={},o=a,e="blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" ");n.proxy={proxy:function t(e,o){return(i[e]||(i[e]=[])).push(o),n.proxy},off:function s(e,o){var t=i[e]||[],r=[];return c(t,function(e){e!==o&&r.push(e)}),t[e]=r,n.proxy}},c(e,function(e){i[e]=[],function r(e,o,t){return"function"!=typeof e.addEventListener?e.attachEvent("on"+o,t):e.addEventListener(o,t,!0)}(o,e,function(o){try{c(i[e],function(e){e(o)})}catch(p){console&&"function"==typeof console.error&&console.error(p.stack)}})})}(r)}r._i=[],r.init=function(e,o,t){var n=r;void 0!==t?n=r[t]=[]:t=s,n.people=n.people||[],n.toString=function(e){var o=s;return t!==s&&(o+="."+t),e||(o+=" (stub)"),o},n.people.toString=function(){return n.toString(1)+".people (stub)"},c("time_event track track_pageview register register_once unregister set_config".split(" "),function(e){!function r(e,o){var t=o.split(".");2===t.length&&(e=e[t[0]],o=t[1]),e[o]=function(){e.push([o].concat(Array.prototype.slice.call(arguments,0)))}}(n,e)}),r._i.push([e,o,t])},r.__SV=1.2,(t=a.createElement("script")).type="text/javascript";try{t.charset=BEFORE_INIT.charset||"utf-8",t.async="undefined"==typeof BEFORE_INIT.async||BEFORE_INIT.async}catch(p){t.charset="utf-8",t.async=!0}"undefined"!=typeof SUGOIO_CUSTOM_LIB_URL?t.src=SUGOIO_CUSTOM_LIB_URL:"file:"===i.location.protocol&&SUGOIO_LIB_URL.match(/^\/\//)?t.src="https:"+SUGOIO_LIB_URL:t.src=SUGOIO_LIB_URL,(n=a.getElementsByTagName("script")[0]).parentNode.insertBefore(t,n),r.callback=function(e){e(r)}}function c(e,o){for(var t=0,r=e.length;t<r;t++)o(e[t],t,e)}}(document,window.sugoio||[]);
    } catch (error) {
        console.error(error);
    }
}

/**
 * 初始化埋点SDK：公共埋点控件
 * @param {*} info 
 */
function initSugoioSDK(info) {
    if(typeof ICBCUtil != 'undefined' && ICBCUtil.isHarmony() && (getChannel() === '3' || typeof sugoio != "object")){   // 鸿蒙适配 手机银行 
        var wapbInfo = typeof info =="object" ? info : {}
        // 监听页面加载事件（载入、刷新）
        window.addEventListener('load', function () {
            wapbInfo.event_type = '浏览';
            handleHitFromFIEPA(wapbInfo);
        })
        // 监听页面点击事件
        document.addEventListener('click', function(event) {
            wapbInfo.event_type = '点击';
            handleHitFromFIEPA(wapbInfo);
        });

    }else{
        try {
            sugoio.init('', { // 项目TOKEN
                project_id: 'F-IEPA', // 项目ID
                api_host: "//" + hitConfig.host + hitConfig.context + "/page/collection", //埋点请求域名
                loaded: function (lib) {
                    // register给需要采集的字段赋值
                    sugoio.register({
                        curmenuid:curPage.columnId,
                        curmenu: getMetaInfo("ICBCChannel"),
                        srcchannel: getQueryString("srcchannel"),
                        transitionid:transitionId,
                        word1:p_bp_init_param,
                        word2:+new Date(),
                        maincis: _icbcHitGetCookie('cisCode') ? _icbcHitGetCookie('cisCode') : "",
                        userid: _icbcHitGetCookie('cisCode') ? _icbcHitGetCookie('cisCode') : ""
                    });
                    if(typeof info =="object"){
                        sugoio.register(info);
                    }
                }, // **sugoio** **sdk** 加载完成回调函数
                debug: false, // 是否启用debug
                isOpen: true,//全埋点开关
                dimensions:[
                    "uagent","curmenuid","curmenu","srcpageurl","scenetype","contentid","srcchannel","transitionid",
                    "sessiontime","areano","areanoname","buttonno","buttonname","buttonseq",
                    "pushtitle","pushcontent","errorid","errordesp",
                    "word1","word2","word3","word4",
                    "event_type","areacode","areaname","noidendifiedcusid","maincis","userid","struid","userlevel",
                    //手机SDK
                    "deviceid","carrier","mobilenetworkchannel","mobilenetworkmode","country","language","timezone",
                    "phonebrand","devicemodel","cpumode","pixelmetric","devicesystem","isroot","appinstallationtime",
                ],//维度设置接口，指明要采集哪些字段
            });
        } catch (error) {
            console.error(error);
        }
    }
}

/**
 * icbc_core.js加载完成，调用getPvClientInfo桥接方法，实现getPvClientInfoCallBack回调方法
 */
function handleICBCCoreJsLoaded() {
    //实现icbc_core.js回调方法：安卓和ios返回数据格式不一致
    ICBCUtil.getPvClientInfoCallBack=function(data){
        try {
            if(typeof data!= "object"){
                data = JSON.parse(data)
            }
        }
        catch(error){
            data = undefined
        }
        sessionStorage.setItem("wapbInfo",JSON.stringify(data))
        initSugoioSDK(data);
    }
    if(typeof ICBCUtil.getPvClientInfo != "undefined"){
        ICBCUtil.getPvClientInfo();
    }
}

/**
 * 获取meta标签中的信息
 */
function getMetaInfo(name) {
    var meta = document.querySelector("[name="+name+"]");
    if(meta){
        return meta.content || "";
    }
    return "";
}

/**
 * 获取搜索引擎
 * @returns 
 */
function getSearchEngine() {
    var ref = document.referrer;
    if(ref==="" || ref.indexOf(location.origin)>-1) {return ""}
    var regexp = new RegExp("\.(icbc|baidu|sougou|so|google|bing|yahoo|ask|aol|naver|duckduckgoog|sm)(\.(com|cn))","ig");
    var match = regexp.exec(ref);
    if(match){
        if(match[1]==="icbc") { return ""; }
        if(match[1]==="so") { return "360sou"; }
        if(match[1]==="sm") { return "shenma"; }
        return match[1];
    }else{
        return "other";
    }
}

/**
 * 获取userAnalysisId
 */
function getUserAnalysisId() {
    var value = localStorage.getItem("icbcUserAnalysisId",value);
    if(value && value.length < 19) return value;
    value = buildUserAnalysisId();
    !disableBP && localStorage.setItem("icbcUserAnalysisId",value);
    return value;
}
/**
 * 构建userid date + digital num：日期+随机数
 * @returns 
 */
function buildUserAnalysisId() {
    var ran = Math.random() * 1000000000;
    var dateStr =new Date(new Date().getTime()+8*60*60*1000).toISOString().substring(0,10).replace(/-/g,"");
    return dateStr + parseInt(ran);
}

/**
 * 生成随机guid数
 */
function guid() {
    function random4() {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    return random4() + random4()+"-"+random4()+"-"+random4()+"-"+random4()+"-"+random4()+random4()+random4();
}

/**
 *  0：PC网站； 1：手机网站；2：开放式网银；3：手机银行；4：微信；99：其他
 */
function getChannel() {
    var ua = navigator.userAgent.toLowerCase();
    if(ua.indexOf("f-wapb")>-1){
        return "3"; //手机银行
    }
    if(ua.indexOf("micromessenger")>-1){
        return "4"; //微信
    }
    var fatherHost = parent !== window? window.location.hostname:parent.window.location.hostname;
    if(fatherHost.indexOf("mybank.icbc")>-1){
        return "2"; //开放式网银
    } 
    if(fatherHost.indexOf(".icbc")>-1){
        if(ua.search(/(android|webos|iphone|ipad|blackberry|windows phone)/)>-1){
            return "1"; 
        }
        return "0";
    }
    return "99";
}

/**
* 获取浏览器
*/
function getBrowser(){
    var ua = navigator.userAgent.toLowerCase(); 
    if(ua.indexOf("compatible")>-1 && ua.indexOf("msie")>-1){
        return "ie"; //<ie11
    }
    if(ua.indexOf("trident")>-1 && ua.indexOf("rv:11.0")>-1){
        return "ie11";
    }
    //部分浏览器ua可能同时包含chrome、safari关键字，因此放在最后匹配
    var rules=["2345","lbbrowser","sogou","maxthon","qq","opera","firefox","edge","chrome","safari"];
    for (var i = 0; i < rules.length; i++) {
        if(ua.indexOf(rules[i])>-1) {
            return rules[i];
        }
    }
    return "other";
}


/**
 * @returns 1：外部进入；2：站内点击；3：直接访问；4：站内搜索；5：交易注入；6：动态页 7:cms系统
 */
function getPvType() {
    var father = parent !== window? window.location: parent.window.location;
    var ref = document.referrer;
    if(father.pathname.search(/\/(webpage|mpage)/i)===0){
        return "6"; //动态页
    }
    if(ref===""){
        return "3"; //直接访问
    }
    if(ref.indexOf("//s.icbc.com.cn")>-1){
        return "4"; //站内搜索
    }
    if(ref.indexOf(father.hostname)>-1 && ref.indexOf(".icbc") > -1 ){
        return "2"; //站内点击(当前页面域名与来源页一致)
    }
    return "1"; //外部进入
}

/**
 * 获取url参数
 * @param {*} name 参数名
 * @param {*} url 需要解析url地址，可选
 * @returns 
 */
function getQueryString(name, url) {
    var reg = new RegExp('(^|&)+'+name+'=([^&]*)(&|$)', "i");
    var path = url || window.location.href;
    var params = path.split("?");
    if (params.length < 2) {
        return "";
    }
    var r = params[1].match(reg);
    if (r) {
        return decodeURI(r[2]);
    }
    return "";
}

/**
 * 获取区域名称data-collecting-aname
 * @param {*} target 
 * @returns 区域名称
 */
function getAreaName(node){
    var target = $(node);
    var areanoname = target.data("collecting-aname") || "";
    if (!areanoname){
        var parents = target.parents("[data-collecting-aname]");
        if(parents.length){
            areanoname = $(parents[0]).data("collecting-aname");
        }
    }
    return areanoname;
}

/**
 * 广告埋点
 * @param {*} info 
 */
function handleAdHit(info) {
    if (document.hidden || disableBP) return;
    var param = {
        userAnalysisId: icbcUserAnalysisId, 
        transitionId: transitionId,
        currentColumn:curPage.columnPath,//当前页面全路径
        columnPageId:curPage.columnId,//当前页面栏目id
        currentPageId:curPage.pageId, 
        currentPageUrl:curPage.pageUrl,
        channelType: channelType,//0-pc 1-手机
        userAgent: userAgent,
        timestamp: parseInt(new Date().getTime()/1000),//时间戳到秒级
        spaceId: info.spaceId || "",
        spaceName: info.spaceName || "",
        //接口返回forwardPageUrl是encodeURI后的数据，此处先decode再采集
        forwardPageUrl: decodeURI(info.forwardPageUrl||""),
        resourceIndex: info.resourceIndex || 1,
        resourceId: info.resourceId ||"",
        resourceColumnId: info.resourceColumnId || "",
        eventType: info.eventType || 1,
    };
    $.ajax({
        type:"GET",
        url:  "//" + hitConfig.host + hitConfig.context + "/data/collection",
        cache: false,
        timeout: 3000,
        data: param,
        xhrFields: {
            withCredentials: false,
        },
    });
}

/**
 * 搜索站点埋点
 * @param {*} info 
 * @returns 
 */
 function handleKeyWordHit(info) {
    var param = JSON.parse(p_bp_init_param);
    param.p_pv_type = info.pvType;
    param.p_search_word = info.searchWord;
    param.p_src_page_id = info.pageId;
    param.p_cur_page_id = info.pageId;
    param.p_cur_channel = info.channel;
    // hitType: '0'刷新触发  '1'点击触发
    if (info.hitType === '0') {
        // 手动触发埋点原因： 无码埋点会在页面刷新和点击时触发，刷新时会调用loaded事件初始化参数，我们注册的参数会被初始化覆盖掉，导致参数无法带出
        var p_param = encodeURIComponent(JSON.stringify(param));
        var sugoioDataArr = sugoio._encode().split("&");
        var wordIndex = '';
        for (var i = 0; i < sugoioDataArr.length; i++) {
            if (sugoioDataArr[i].indexOf("word1=") === 0) {
                wordIndex = i;
            }
        }
        sugoioDataArr[wordIndex] = "word1="+p_param;
        var urlData = sugoioDataArr.join('&');
        $.ajax({
            type:"GET",
            url:  "//" + hitConfig.host + hitConfig.context + "/page/collection?" + urlData,
            cache: false,
            timeout: 3000,
            xhrFields: {
                withCredentials: false,
            },
        });
    } else {
        handleClientHit({
            word1: JSON.stringify(param)
        });
    }
}

/**
 * 页面埋点：点击事件
 * @param {*} info 
 */
function handleClientHit(info) {
    if(disableBP) return;
    if(typeof info !="object") return;
    if(typeof ICBCUtil != 'undefined' && ICBCUtil.isHarmony() && (getChannel() === '3' || typeof sugoio != "object")){  // 鸿蒙适配 手机银行 
        var wapbInfo = JSON.parse(sessionStorage.getItem("wapbInfo")||"{}");
        info.event_type = '点击';
        handleHitFromFIEPA(wapbInfo,info);
    }else{
        // 注册自定义参数
        sugoio.register(info);
        // 注册之后再将参数置为空，作用：实现业务自定义区域埋点的功能，点击时将参数注册上去，之后点击其他地方就不需要这个参数了，因此置为空
        setTimeout(function() {
            sugoio.register({buttonname: '', areanoname: '', word1: p_bp_init_param, word4: ''});
        }, 0);
    }
}
/**
 * 新客行-下线
 */
 function handleNJsHit(nJSParam) {
    return;
}
function assignFun(a, b) {
    var aDeep = JSON.parse(JSON.stringify(a))
    var bDeep = JSON.parse(JSON.stringify(b))
    for (var key in bDeep) {
        aDeep[key] = bDeep[key];
    }
    return aDeep
}
/**
 * 自主发送埋点请求（兼容手机银行、鸿蒙系统）
 * @param {*} wapbInfo  手机银行客户端信息
 * @param {*} clientInfo  业务自定义参数
 */
 function handleHitFromFIEPA(wapbInfo,clientInfo) {
    var url = "//" + hitConfig.host + hitConfig.context + "/page/collection";
    var today = new Date();
    var dd = String(today.getDate());
    var mm = String(today.getMonth() + 1);  //January is 0!
    var yyyy = today.getFullYear();
    var hour = String(today.getHours());
    var minute = String(today.getMinutes());
    var second = String(today.getSeconds());

    dd = dd.length > 1 ? dd : '0' + dd;
    mm = mm.length > 1 ? mm : '0' + mm;
    hour = hour.length > 1 ? hour : '0' + hour;
    minute = minute.length > 1 ? minute : '0' + minute;
    second = second.length > 1 ? second : '0' + second;

    today = yyyy+mm+dd;
    var transtime = hour+minute+second;
    
    // 默认入参
    var params = {
        curmenuid: curPage.columnId || "",
        curmenu: getMetaInfo("ICBCChannel"),
        srcchannel: getQueryString("srcchannel"),
        transitionid: transitionId,
        word1: p_bp_init_param,
        word2: +new Date(),
        word3: "",
        word4: "",  
        maincis: _icbcHitGetCookie('cisCode') ? _icbcHitGetCookie('cisCode') : "",
        userid: _icbcHitGetCookie('cisCode') ? _icbcHitGetCookie('cisCode') : "",
        buttonname: "",
        areanoname: "",
        event_type: "",
        transdate: Number(today),
        transtime: transtime,
        srcpageurl: p_bp_init_param.p_src_page_url || "",
        uagent: userAgent,
        stat_ss:"",
        sessionid:"",
        pvtype:1,
        srcpageno:"",
        srcpagename:p_bp_init_param.p_src_page_name || "",
        curpageno:"",
        curpagename:p_bp_init_param.p_cur_page_name || "",
        curpageurl:p_bp_init_param.p_cur_page_url || "",
        staytime:"",
        title:"",
        scenetype:"",
        contentid:"",
        sessiontime:"",
        areano:"",
        buttonno:"",
        buttonseq:"",
        pushtitle:"",
        pushcontent:"",
        errorid:"",
        errordesp:"",
        areacode:"",
        areaname:"",
        noidendifiedcusid:"",
        struid:"",
        userlevel:""
    }
    if(typeof wapbInfo =="object"){
        for (var key in wapbInfo) {
            if (wapbInfo.hasOwnProperty(key)) {
                wapbInfo[key] = decodeURIComponent(wapbInfo[key]);
            }
        }
        params = assignFun(params, wapbInfo);
    }
    if(typeof clientInfo =="object"){
        for (var key in clientInfo) {
            if (clientInfo.hasOwnProperty(key)) {
                clientInfo[key] = decodeURIComponent(clientInfo[key]);
            }
        }
        params = assignFun(params, clientInfo);
    }
    // 格式转换
    function jsonToUrlParams(jsonObj) {
        return Object.keys(jsonObj).map(function(key) {
            return encodeURIComponent(key) + '=' + encodeURIComponent(jsonObj[key]);
        }).join('&');
    }
    var urlParams = jsonToUrlParams(params);

    if(typeof _ajaxRequest !="undefined"){
        _ajaxRequest.post(
            url+'?'+urlParams, 
            '', 
            function (res) {}
        )
    }else if(typeof $ !="undefined"){
        $.ajax({
            type:"POST",
            url: url+'?'+urlParams,
            cache: false,
            async: true,
            crossDomain: true,
            timeout: 3000,
            //data: JSON.stringify(params),
            xhrFields:{
                withCredentials: false,
            },
        });
    }
}
